package com.damie.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dadie.Domain.ShopDataDomain;
import com.dadie.Domain.ShopDomain;
import com.dadie.Domain.ShopShelvesDomain;
import com.dadie.Dto.ShopDataDto;
import com.dadie.Dto.ShopDto;
import com.dadie.parame.ShopDataParame;
import com.dadie.parame.ShopParame;
import com.dadie.parame.UpdateShopParam;
import com.damie.mapper.ShopDataMapper;
import com.damie.mapper.ShopMapper;
import com.damie.mapper.ShopShelvesMapper;
import com.damie.service.ShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.damie.uilt.Copy;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alon
 * @since 2021-01-23
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDomain> implements ShopService {

    @Resource
    private ShopMapper mapper;

    @Resource
    private ShopDataMapper dataMapper;

    @Resource
    private ShopShelvesMapper shopShelvesMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public ShopDto addProduct(ShopParame shopParame) {
        QueryWrapper<ShopDomain> wrapper = new QueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotNull(shopParame.getProductName()),"product_name",shopParame.getProductName());
        ShopDomain obj = mapper.selectOne(wrapper);
        List<ShopDataParame> dataParameList = shopParame.getDataParameList();
        if (ObjectUtils.isNotEmpty(obj)){
            obj.setProductInventory(obj.getProductInventory()+shopParame.getProductInventory());
            mapper.updateById(obj);
            forAdd(dataParameList,obj.getProductId());
            return (ShopDto) Copy.copy(obj,new ShopDto());
        }
        ShopDomain copy = (ShopDomain) Copy.copy(shopParame,new ShopDomain());
        copy.setProductStatus("1");
        mapper.insert(copy);
        String productId = copy.getProductId();
        forAdd(dataParameList,productId);
        return (ShopDto) Copy.copy(copy,new ShopDto());
    }

    public void forAdd(List<ShopDataParame> dataParameList,String productId){
        for (ShopDataParame list:dataParameList) {
            QueryWrapper<ShopDataDomain> shopDataDomainQueryWrapper = new QueryWrapper<>();
            shopDataDomainQueryWrapper.eq("shop_url", list.getShopUrl());
            shopDataDomainQueryWrapper.eq("product_id", productId);
            List<ShopDataDomain> shopDataDomains = dataMapper.selectList(shopDataDomainQueryWrapper);
            System.out.println(list);
            if (ObjectUtils.isEmpty(shopDataDomains)) {
                ShopDataDomain copy1 = (ShopDataDomain) Copy.copy(list, new ShopDataDomain());
                copy1.setProductId(productId);
                copy1.setShopLeve(list.getShopLeve());
                copy1.setShopUrl(list.getShopUrl());
                System.out.println(copy1);
                dataMapper.insert(copy1);
            }
        }
    }

    @Override
    @Transactional
    public Page<ShopDto> selectAllProduct(Integer index, Integer size, String shopName) {
        QueryWrapper<ShopDomain> shopDomainQueryWrapper = new QueryWrapper<>();
        if (shopName!=null &&! "".equals(shopName)){
            shopDomainQueryWrapper.like("product_name",shopName);
        }
        Page<ShopDomain> shopDomainPage = mapper.selectPage(new Page<>(index, size), shopDomainQueryWrapper);
        List<ShopDto> collect = shopDomainPage.getRecords().stream().map(shopDomain -> {
            QueryWrapper<ShopDataDomain> shopDataDomainQueryWrapper = new QueryWrapper<>();
            shopDataDomainQueryWrapper.eq("product_id",shopDomain.getProductId());
            List<ShopDataDomain> shopDataDomains = dataMapper.selectList(shopDataDomainQueryWrapper);
            List<ShopDataDto> se = shopDataDomains.stream().map(shopDataDomain -> {
                return (ShopDataDto) Copy.copy(shopDataDomain, new ShopDataDto());
            }).collect(Collectors.toList());
            ShopDto copy = (ShopDto) Copy.copy(shopDomain, new ShopDto());
            copy.setShopDataParames(se);
            return copy;
        }).collect(Collectors.toList());
        Page<ShopDto> shopDtoPage = new Page<>();
        BeanUtils.copyProperties(shopDomainPage,shopDtoPage);
        shopDtoPage.setRecords(collect);
        return shopDtoPage;
    }

    @Transactional
    @Override
    public ShopDto deleteByIdProduct(String pid) {
        QueryWrapper<ShopDomain> shopDomainQueryWrapper = new QueryWrapper<>();
        shopDomainQueryWrapper.eq(pid!=null,"product_id",pid);
        ShopDomain shopDomain = mapper.selectOne(shopDomainQueryWrapper);
        if(ObjectUtils.isNotEmpty(shopDomain)){
            QueryWrapper<ShopShelvesDomain> shopShelvesDomainQueryWrapper = new QueryWrapper<>();
            shopShelvesDomainQueryWrapper.eq("product_id",pid);
            List<ShopShelvesDomain> shopShelvesDomains = shopShelvesMapper.selectList(shopShelvesDomainQueryWrapper);
            int size = shopShelvesDomains.size();
            if (size==0){
                //该商品没有上架可直接删除商品
                mapper.deleteById(shopDomain);
                String productId = shopDomain.getProductId();
                HashMap<String, Object> p = new HashMap<>();
                p.put("product_id",productId);
                dataMapper.deleteByMap(p);
                return (ShopDto) Copy.copy(shopDomain,new ShopDto());
            }else {
                int count1 = 0;
                for(ShopShelvesDomain object:shopShelvesDomains){
                    Integer productInventory = object.getProductUpNum();
                    count1 += productInventory;
                    shopShelvesMapper.deleteById(object);
                }
                shopDomain.setProductInventory(shopDomain.getProductInventory()+count1);
                mapper.updateById(shopDomain);
                mapper.deleteById(shopDomain);
                HashMap<String, Object> p = new HashMap<>();
                p.put("product_id",shopDomain.getProductId());
                dataMapper.deleteByMap(p);
                return (ShopDto) Copy.copy(shopDomain,new ShopDto());
            }
        }
        return null;
    }

    @Override
    @Transactional
    public ShopDto updateByProduct(UpdateShopParam shopParame) {
        //判断是否该商品是否存在以及是否上架
        QueryWrapper<ShopDomain> wrapper = new QueryWrapper<>();
        wrapper.eq (shopParame.getProductId()!=null,"product_id",shopParame.getProductId());
        ShopDomain shopDomain = mapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(shopDomain)){
            //该商品在库中，接下来判断是否上架
//            List<ShopDomain> range = redisTemplate.opsForList().range("productId:" + shopDomain.getProductId(), 0, -1);
//                if(range!=null) {
//                    //该商品已经上架要修改上架商品的描述和商品名
//                    shopDomain.setProductName(shopParame.getProductName());
//                    mapper.updateById(shopDomain);
//                    ArrayList<ShopDomain> shopDomains = new ArrayList<>();
//                    int size = range.size();
//                    while (size>0) {
//                        Object os = redisTemplate.opsForList().rightPop("productId:" + shopDomain.getProductId());
//                        String s = os.toString();
//                        String substring = s.substring(s.indexOf("productName="), s.indexOf(", productTotal"));
//                        String s1 = substring.replaceFirst("productName=", "");
//                        String wqw = s.replace(s1, shopParame.getProductName());
//                        System.out.println(wqw);
//                        size--;
//                    }
//                    redisTemplate.opsForList().rightPushAll("productId:" + shopDomain.getProductId(),shopDomains);
//                    return (ShopDto) Copy.copy(shopDomain,new ShopDto());
//                }else {
                    //没有上架则直接修改
                shopDomain.setProductName(shopParame.getProductName());
                mapper.updateById(shopDomain);
                return (ShopDto) Copy.copy(shopDomain,new ShopDto());

            }
            throw new RuntimeException("参数异常");
        }

    @Override
    @Transactional
    public ShopDto updateByProductNum(String pid, Integer num) {
        ShopDomain shopDomain = mapper.selectById(pid);
        if (ObjectUtils.isNotEmpty(shopDomain)){
            System.out.println(shopDomain.getProductInventory()+":"+num);
            if (shopDomain.getProductInventory()-num>=0){
                shopDomain.setProductInventory(shopDomain.getProductInventory()-num);
                mapper.updateById(shopDomain);
                return (ShopDto) Copy.copy(shopDomain,new ShopDto());
            }
        }
        throw new RuntimeException("减少数量超过库存");
    }
}


